{# 继承父类模板 #}
{% extends 'templates/LR/base.html' %}
{% load static %}

{# 重写模块，定义页面个性化内容 #}
{% block header %}
    {% include 'templates/LR/header.html' %}
{% endblock %}

{% block link %}
    <link rel="stylesheet" href="{% static 'css/chat/post.css' %}">
{% endblock %}

{% block main %}

    <div class="container">
        <div class="content">
            <div class="left-box">
                <div class="user-desc">
                    <a href="#"><img src="/static/media/{{ author.cover }}" alt="user头像" class="user-cover"></a>
                    <a href="#"><span class="user-name">{{ post.user.username }}</span></a>
                    <span class="user-desc">{{ author.signature }}</span>
                </div>
                <div class="user-data">
                    <dl class="user-data-info">
                        <a href="#">
                            <dt>
                                <span class="count">{{ work_count }}</span>
                            </dt>
                            <dd class="font">原创</dd>
                        </a>
                    </dl>
                    <dl class="user-data-info">
                        <dt>
                            <span class="count">{{ follow_count }}</span>
                        </dt>
                        <dd class="font">粉丝</dd>
                    </dl>
                    <dl class="user-data-info">
                        <dt>
                            <span class="count">{{ like_count }}</span>
                        </dt>
                        <dd class="font">获赞</dd>
                    </dl>
                    <dl class="user-data-info">
                        <dt>
                            <span class="count">{{ collect_count }}</span>
                        </dt>
                        <dd class="font">收藏</dd>
                    </dl>
                </div>
                <div class="relate">
                    <a href="#" class="letter">私信</a>
                    <a href="#" class="follow">关注</a>
                </div>
            </div>
            <div class="right-box">
                <div class="info">
                    <h1>{{ post.title }}</h1>
                    <div class="tags">
                        <div>
                            <span>作者{{ post.user.username }}</span>
                            <span>发布时间{{ post.create_time }}</span>
                        </div>
                        <div>
                            <span>👍</span>
                            <span class="tag">{{ like_count_all }}</span>
                            <span>评论</span>
                            <span class="tag">{{ comment_count }}</span>
                        </div>
                    </div>
                </div>
                <div class="article">
                    {{ post.content }}
                </div>
            </div>
        </div>

        <div class="comment-section">
            <h2>评论</h2>
            {% for comment_data in comments_data %}
                <div class="parent-comment">
                    <!-- 用户信息 -->
                    <div class="user-info">
                        <a href="#">
                            <img src="/static/media/img/{{ comment_data.userdetails.cover }}" alt="头像" class="avatar">
                        </a>
                        <div class="user-details">
                            <span><a href="#" class="username">{{ comment_data.parent.user.username }}</a></span>
                            {% if comment_data.parent.user == post.user %}
                                <span class="author-tag">作者</span>
                            {% endif %}
                            <span class="comment-date">{{ comment_data.parent.created_at|date:"Y-m-d H:i" }}</span>
                        </div>
                    </div>

                    <!-- 评论内容 -->
                    <div class="comment-content">
                        {{ comment_data.parent.content }}
                    </div>

                    <div class="function" style="text-align: right">
                        <button class="replay" data-parent="{{ comment_data.parent.id }}">回复</button>
                        <button class="like-comment" data-parent="{{ comment_data.parent.id }}">👍</button>
                    </div>

                    <div class="reply-box" id="reply-box-{{ comment_data.parent.id }}" style="display: none">
                        <input type="text" class="reply-input" placeholder="回复{{ comment_data.parent.user.username }}"
                               data-parent="{{ comment_data.parent.id }}">
                        <button class="reply-btn">回复</button>
                    </div>

                    <!-- 查看回复 -->
                    {% if comment_data.children %}
                        <button class="show-replies" data-parent="{{ comment_data.parent.id }}">
                            查看回复 ({{ comment_data.children|length }})
                        </button>
                        <div class="child-comments" id="child-comments-{{ comment_data.parent.id }}"
                             style="display:none">
                            {#子级评论将在点击按钮后异步加载#}
                        </div>
                    {% endif %}
                    <!-- 回复框 -->

                </div>
            {% endfor %}
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            document.addEventListener("click", function (event) {
                // 事件委托 - 处理"查看回复"按钮
                if (event.target.classList.contains("show-replies")) {
                    const parentId = event.target.getAttribute("data-parent");
                    const childContainer = document.getElementById(`child-comments-${parentId}`);

                    if (childContainer.style.display === "none") {
                        event.target.innerText = "加载中...";
                        fetch(`/chat/load_child_comments/${parentId}/`)
                            .then(response => response.json())
                            .then(data => {
                                let html = "";
                                data.child_comments.forEach(child_comment => {
                                    html += `
                                <div class="child-comment" style="align-items: center;">
                                    <a href="#"><img src="/static/media/${child_comment.cover}" class="avatar" alt="评论者头像"></a>
                                    <div class="user-details">
                                        <span><a href="#" class="username">${child_comment.username}:</a></span>
                                        <span class="comment-date">${child_comment.created_at}</span>
                                    </div>

                                <div class="comment-content">
                                    ${child_comment.content}
                                </div>
                                <div class="function" style="text-align: right">
                                    <button class="replay" data-parent="${child_comment.id}">回复</button>
                                    <button class="like-comment">👍</button>
                                </div>
                                <div class="reply-box" id="reply-box-${child_comment.id}" style="display: none">
                                    <input type="text" class="reply-input" placeholder="回复${child_comment.username}" data-parent="${child_comment.id}">
                                    <button class="reply-btn">回复</button>
                                </div>
                                ${child_comment.child_comments.length > 0 ? `
                                    <button class="show-replies" data-parent="${child_comment.id}">
                                        查看回复 (${child_comment.child_comments.length})
                                    </button>
                                    <div class="child-comments" id="child-comments-${child_comment.id}" style="display:none"></div>
                                ` : ''}
                                </div>
                            `;
                                });
                                childContainer.innerHTML = html;
                                childContainer.style.display = "block";
                                event.target.innerText = "收起回复";
                            });
                    } else {
                        childContainer.style.display = "none";
                        event.target.innerText = `查看回复 (${childContainer.querySelectorAll(".child-comment").length})`;
                    }
                }

                // 事件委托 - 处理"回复"按钮
                if (event.target.classList.contains("replay")) {
                    const parentId = event.target.getAttribute('data-parent');
                    const replyBox = document.getElementById(`reply-box-${parentId}`);
                    replyBox.style.display = replyBox.style.display === "none" ? "block" : "none";
                }

                // 事件委托 - 处理"提交回复"按钮
                if (event.target.classList.contains("reply-btn")) {
                    const input = event.target.previousElementSibling;
                    const parentId = input.getAttribute("data-parent");
                    const content = input.value.trim();
                    const postId = document.getElementById("post-id").value; // 假设页面有个隐藏的 `post-id` input

                    if (!content) {
                        alert("评论内容不能为空！");
                        return;
                    }

                    fetch('/chat/add_comment/', {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "X-CSRFToken": getCookie("csrftoken")  // Django 需要 CSRF 保护
                        },
                        body: new URLSearchParams({
                            post_id: postId,
                            content: content,
                            parent_id: parentId
                        })
                    })

                        .then(response => response.json())
                        .then(data => {
                            if (data.error) {
                                alert("评论失败，请重试！");
                                return;
                            }

                            // 插入新评论到页面
                            const newCommentHtml = `
                    <div class="child-comment">
                        <a href="#"><img src="/static/media/default_avatar.jpg" class="avatar" alt="评论者头像"></a>
                        <div class="user-details">
                            <span><a href="#" class="username">${data.username}:</a></span>
                            <span class="comment-date">${data.created_at}</span>
                        </div>
                        <div class="comment-content">${data.content}</div>
                        <div class="function" style="text-align: right">
                            <button class="replay" data-parent="${data.parent_id}">回复</button>
                            <button class="like-comment">👍</button>
                        </div>
                    </div>
                `;

                            const parentContainer = document.getElementById(`child-comments-${parentId}`) || document.getElementById("main-comments");
                            parentContainer.insertAdjacentHTML("beforeend", newCommentHtml);

                            // 清空输入框
                            input.value = "";
                        });
                }
            });


            // 获取 CSRF 令牌
            function getCookie(name) {
                let cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    document.cookie.split(';').forEach(cookie => {
                        cookie = cookie.trim();
                        if (cookie.startsWith(name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        }
                    });
                }
                return cookieValue;
            }
        });

    </script>

{% endblock %}

